/*
 * @Author: Eric 184179023@.com
 * @Date: 2025-02-11 09:17:34
 * @LastEditors: bug巫师 184179023@qq.com
 * @LastEditTime: 2025-03-02 10:05:40
 * @FilePath: \ABS.OA\cloudfunctions\mcloud\project\oa\service\admin\admin_flow_service.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/**
 * Notes:工作流后台管理
 * Ver : Framework 1.0.0
 * Date: 2024-06-02 07:48:00 
 */

const BaseProjectAdminService = require('./base_project_admin_service.js');
const exportUtil = require('../../../../framework/helpers/export_util.js');
const dataUtil = require('../../../../framework/helpers/data_util.js');
const util = require('../../../../framework/helpers/util.js');
const timeUtil = require('../../../../framework/helpers/time_util.js');

const FlowModel = require('../config/models_config').flow_model;

// 导出数据KEY
const EXPORT_FLOW_DATA_KEY = 'EXPORT_FLOW_DATA';

class AdminFlowService extends BaseProjectAdminService {

	async getAdminFlowList({
		search, // 搜索条件
		sortType, // 搜索菜单
		sortVal, // 搜索菜单
		orderBy, // 排序
		whereEx, //附加查询条件
		page,
		size,
		isTotal = true,
		oldTotal
	}) {

		orderBy = orderBy || {
			'FLOW_ADD_TIME': 'desc'
		};
		let fields = 'FLOW_NO,FLOW_DEPTS,FLOW_CATE_ID,FLOW_TO_STEP,FLOW_NOW_NATIVE_DEPT,FLOW_CATE_NAME,FLOW_TO_DEPT,FLOW_NOW_STEP,FLOW_OBJ,FLOW_USER_DEPT,FLOW_NOW_USER_NAME,FLOW_NOW_DEPT,FLOW_STATUS,FLOW_ADD_TIME';

		let where = {};
		where.and = {
			_pid: this.getProjectId() //复杂的查询在此处标注PID
		};

		if (util.isDefined(search) && search) {
			where.or = [
				{ ['FLOW_OBJ.person']: ['like', search] },
				{ ['FLOW_NO']: Number(search) },
			];

		} else if (sortType && util.isDefined(sortVal)) {
			// 搜索菜单
			switch (sortType) {
				case 'cateId': {
					where.and.FLOW_CATE_ID = String(sortVal);
					break;
				}
				case 'status': {
					where.and.FLOW_STATUS = Number(sortVal);
					break;
				}
				case 'sort': {
					orderBy = this.fmtOrderBySort(sortVal, 'FLOW_ADD_TIME');
					break;
				}

			}
		}

		return await FlowModel.getList(where, fields, orderBy, page, size, isTotal, oldTotal);
	}

	/**修改资讯状态 */
	async statusFlow(id, status) {
		// 状态值校验
		if (![FlowModel.STATUS.RUN, FlowModel.STATUS.REJECT, FlowModel.STATUS.OVER].includes(status)) 
			this.AppError('状态值错误，可选值：' + FlowModel.STATUS.RUN + '(审批中),' + FlowModel.STATUS.REJECT + '(驳回),' + FlowModel.STATUS.OVER + '(完成)');
		
		// 查询工作流是否存在
		let where = {
			_id: id
		};
		let flow = await FlowModel.getOne(where);
		if (!flow) this.AppError('该工作流不存在');
		
		// 如果状态相同，无需更新
		if (flow.FLOW_STATUS === status) {
			return;
		}
		
		// 更新流程状态
		let data = {
			FLOW_STATUS: status,
			FLOW_EDIT_TIME: this._timestamp,
			FLOW_EDIT_IP: this._ip
		};
		
		// 如果是设置为"驳回"或"完成"，需要更新其他相关字段
		if (status === FlowModel.STATUS.REJECT || status === FlowModel.STATUS.OVER) {
			data.FLOW_TO_DEPT = '';
			data.FLOW_TO_NATIVE_DEPT = '';
			data.FLOW_TO_STEP = -1;
		}
		
		// 执行更新
		await FlowModel.edit(where, data);
	}


	// #####################导出数据

	/**获取数据 */
	async getFlowDataURL() {
		return await exportUtil.getExportDataURL(EXPORT_FLOW_DATA_KEY);
	}

	/**删除数据 */
	async deleteFlowDataExcel() {
		return await exportUtil.deleteDataExcel(EXPORT_FLOW_DATA_KEY);
	}

	/**导出数据 */
	async exportFlowDataExcel({ start, end, cateId, status, fields }) {
		console.log('[FLOW_EXPORT] Input params:', { start, end, cateId, status });
		
		// 查询条件
		let where = {};
		where.and = {
			_pid: this.getProjectId()
		};

		// 日期范围处理 - 确保日期格式正确
		if (start && end) {
			let startDate = timeUtil.time2Timestamp(start + ' 00:00:00');
			let endDate = timeUtil.time2Timestamp(end + ' 23:59:59');
			console.log('[FLOW_EXPORT] Date range:', { startDate, endDate, start, end });
			where.and.FLOW_ADD_TIME = ['between', startDate, endDate];
		} else if (start) {
			let startDate = timeUtil.time2Timestamp(start + ' 00:00:00');
			console.log('[FLOW_EXPORT] Start date:', { startDate, start });
			where.and.FLOW_ADD_TIME = ['>=', startDate];
		} else if (end) {
			let endDate = timeUtil.time2Timestamp(end + ' 23:59:59');
			console.log('[FLOW_EXPORT] End date:', { endDate, end });
			where.and.FLOW_ADD_TIME = ['<=', endDate];
		}

		// 分类条件
		if (util.isDefined(cateId) && cateId && cateId != '0') {
			where.and.FLOW_CATE_ID = String(cateId);
		}

		// 状态条件 - 999表示"全部"，不应添加到查询条件中
		if (util.isDefined(status) && status != '' && status != '999' && status != 999) {
			where.and.FLOW_STATUS = Number(status);
		}

		// 添加调试信息
		console.log('[FLOW_EXPORT] Final query conditions:', JSON.stringify(where));

		// 简单查询先测试是否有记录
		let count = await FlowModel.count({_pid: this.getProjectId()});
		console.log('[FLOW_EXPORT] Total records in collection:', count);

		// 排序
		let orderBy = {
			'FLOW_ADD_TIME': 'desc'
		};

		// 指定要查询的数据库字段，不使用传入的fields参数
		let dbFields = 'FLOW_NO,FLOW_DEPTS,FLOW_CATE_ID,FLOW_CATE_NAME,FLOW_TO_STEP,FLOW_NOW_STEP,FLOW_OBJ,FLOW_USER_DEPT,FLOW_NOW_USER_NAME,FLOW_NOW_DEPT,FLOW_STATUS,FLOW_ADD_TIME';

		// 先进行简单查询，不附加任何过滤条件
		let simpleList = await FlowModel.getAll({_pid: this.getProjectId()}, dbFields, orderBy, 5);
		console.log('[FLOW_EXPORT] Sample records data:', JSON.stringify(simpleList.slice(0, 1)));

		// 查询数据
		let list = await FlowModel.getAll(where, dbFields, orderBy, 10000);
		
		// 记录查询结果数量
		console.log('[FLOW_EXPORT] Query result count:', list.length);
		
		if (list.length == 0) {
			console.log('[FLOW_EXPORT] Warning: No data found with the current query conditions');
			
			// 即使没有数据，也要生成一个只有表头的Excel
			let header = [
				'编号', 
				'流程分类', 
				'申请人', 
				'申请部门', 
				'当前步骤', 
				'当前审批人', 
				'当前审批部门', 
				'状态', 
				'申请时间'
			];
			
			let data = [header]; // 只包含表头的数据
			let sheetName = '审批记录(无数据)';
			
			return await exportUtil.exportDataExcel(EXPORT_FLOW_DATA_KEY, sheetName, 0, data);
		}

		// 表头和字段映射
		let header = [
			'编号', 
			'流程分类', 
			'申请人', 
			'申请部门', 
			'当前步骤', 
			'当前审批人', 
			'当前审批部门', 
			'状态', 
			'申请时间'
		];
		
		// 需要导出的字段
		let exportFields = [
			'FLOW_NO', 
			'FLOW_CATE_NAME', 
			'FLOW_PERSON', 
			'FLOW_USER_DEPT', 
			'FLOW_NOW_STEP', 
			'FLOW_NOW_USER_NAME', 
			'FLOW_NOW_DEPT', 
			'FLOW_STATUS_DESC', 
			'FLOW_ADD_TIME'
		];
		
		// 构建行数据的二维数组
		let data = [];
		
		// 先放入表头
		data.push(header);
		
		// 数据格式化并添加到导出数组
		for (let k = 0; k < list.length; k++) {
			let row = [];
			
			// 格式化状态
			let statusDesc = '';
			switch (list[k].FLOW_STATUS) {
				case 0: statusDesc = '待审批'; break;
				case 1: statusDesc = '已通过'; break;
				case 8: statusDesc = '已退回'; break;
				case 9: statusDesc = '已取消'; break;
				default: statusDesc = '未知';
			}
			list[k].FLOW_STATUS_DESC = statusDesc;
			
			// 提取申请人信息
			if (list[k].FLOW_OBJ && list[k].FLOW_OBJ.person) {
				list[k].FLOW_PERSON = list[k].FLOW_OBJ.person;
			} else {
				list[k].FLOW_PERSON = '';
			}
			
			// 按照exportFields的顺序添加数据到行
			for (let i = 0; i < exportFields.length; i++) {
				let field = exportFields[i];
				let value = list[k][field];
				
				// 处理时间格式
				if (field === 'FLOW_ADD_TIME' && value) {
					value = timeUtil.timestamp2Time(value);
				}
				
				row.push(value || '');
			}
			
			// 将行添加到数据数组
			data.push(row);
		}
		
		// 设置一个合法的工作表名称（不超过31个字符）
		let sheetName = '审批记录';
		
		// 导出数据
		return await exportUtil.exportDataExcel(EXPORT_FLOW_DATA_KEY, sheetName, list.length, data);
	}

}

module.exports = AdminFlowService;